package com.aiyu.camerademo

import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.PixelCopy
import android.view.SurfaceView
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.drawToBitmap
import androidx.core.view.isVisible
import com.aiyu.camerademo.databinding.ActivityMainBinding
import com.lib.FunSDK
import com.lib.MsgContent
import com.manager.account.BaseAccountManager
import com.manager.account.XMAccountManager
import com.manager.db.XMDevInfo
import com.manager.device.DeviceManager
import com.manager.device.DeviceManager.OnDevManagerListener
import com.manager.device.media.monitor.MonitorManager


class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"
    private val viewBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private var isNeedGetDevRandomUserPwdAgain = true // 是否需要重新获取随机用户名和密码
    private var isNeedGetCloudTryNum = true // 是否需要获取云端试用数

    //    private var videoView: GLSurfaceView? = null // 是否需要获取设备信息
    private var devList: MutableList<XMDevInfo>? = null;
    private var surfaceView: SurfaceView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(viewBinding.root)
        initView()

    }

    private fun initView() {
        viewBinding.apply {
            btnSearchCamera.setOnClickListener {
                // 搜索局域网内的摄像头
                DeviceManager.getInstance().searchLanDevice(
                    object : DeviceManager.OnSearchLocalDevListener {
                        override fun onSearchLocalDevResult(devList: MutableList<XMDevInfo>?) {
                            if (devList == null) {
                                return
                            }

                            this@MainActivity.devList = devList
                            Toast.makeText(
                                this@MainActivity,
                                "搜索到${devList.size}个设备",
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
                )
            }

            viewBinding.camera1.setOnClickListener {
                devList?.get(0)?.let { it1 -> showDevPreview(flCameraPreview, it1) }
            }
            viewBinding.camera2.setOnClickListener {
                devList?.get(1)?.let { it1 -> showDevPreview(viewBinding.flCameraPreview2, it1) }
            }
            viewBinding.cutImage.setOnClickListener {
                if (!viewBinding.iv.isVisible) {
                    if (surfaceView != null) {
                        var bitmap = getBitmap(surfaceView!!)

                        viewBinding.iv.setImageBitmap(bitmap)
                    } else {
                        Toast.makeText(this@MainActivity, "surfaceView is null", Toast.LENGTH_SHORT)
                            .show()
                    }
                    viewBinding.iv.isVisible = true
                }else {
                    viewBinding.iv.isVisible = false
                }
            }
        }
    }

    fun getBitmap(surfaceView: SurfaceView): Bitmap {
        var startTime = System.currentTimeMillis()
        val bitmap = Bitmap.createBitmap(surfaceView.width, surfaceView.height, Bitmap.Config.ARGB_8888)

        PixelCopy.request(surfaceView, bitmap, { copyResult ->
            if (PixelCopy.SUCCESS == copyResult) {
                // onSuccessCallback(bitmap)
                var endTime = System.currentTimeMillis()
                Log.d("MainActivity", "获取图片耗时：${endTime - startTime}ms")
            } else {
                // onErrorCallback()
            }
        }, surfaceView.handler)
        return bitmap
    }

    private fun showDevPreview(preview: ViewGroup, devInfo: XMDevInfo) {
        val mediaManager: MonitorManager =
            DeviceManager.getInstance().createMonitorPlayer(preview, devInfo.devId)
//        mediaManager.setPlayMode(Define.MEDIA_DATA_TYPE_YUV_NOT_DISPLAY)
        surfaceView = mediaManager.surfaceView

//        mediaManager.setOnMediaManagerListener(object : MediaManager.OnMediaManagerYUVListener {
//            override fun onMediaPlayState(p0: PlayerAttribute<*>?, p1: Int) {
//
//            }
//
//            override fun onFailed(p0: PlayerAttribute<*>?, p1: Int, p2: Int) {
//            }
//
//            override fun onShowRateAndTime(
//                p0: PlayerAttribute<*>?,
//                p1: Boolean,
//                p2: String?,
//                p3: Long
//            ) {
//            }
//
//            override fun onVideoBufferEnd(p0: PlayerAttribute<*>?, p1: MsgContent?) {
//            }
//
//            override fun onPlayStateClick(p0: View?) {
//            }
//
//            override fun onResultYUVData(
//                p0: PlayerAttribute<*>?,
//                p1: Int,
//                p2: Int,
//                p3: ByteArray?
//            ) {
//                //yuv数据
//                Log.e(TAG, "onResultYUVData: ${p3?.size}" )
//
//            }
//
//        })
        mediaManager.startMonitor()
    }

    private fun getDevRandomUserPwd(xmDevInfo: XMDevInfo) {
        DeviceManager.getInstance()
            .getDevRandomUserPwd(xmDevInfo, object : OnDevManagerListener<Any?> {
                override fun onSuccess(devId: String, operationType: Int, result: Any?) {
                    loginDev(xmDevInfo)
                }

                override fun onFailed(devId: String, msgId: Int, jsonName: String, errorId: Int) {
                    //获取随机用户名和密码因为超时失败的话，可尝试重试
                    if (isNeedGetDevRandomUserPwdAgain && (errorId == -10005 || errorId == -100000)) {
                        //如果获取随机用户名密码超时的话，可以延时1s重试一次
                        Handler(Looper.getMainLooper()).postDelayed(Runnable {
                            getDevRandomUserPwd(
                                xmDevInfo
                            )
                        }, 1000)

                        isNeedGetDevRandomUserPwdAgain = false
                        return
                    }

//                    if (errorId == -400009) {
//                        //如果不支持随机用户名密码的话，就以 用户名：admin 密码为空登录设备
//                        //是否要将该设备从其他账号下移除
//                        XMPromptDlg.onShow(iDevQuickConnectView.getContext(),
//                            iDevQuickConnectView.getContext()
//                                .getString(R.string.is_need_delete_dev_from_other_account),
//                            { addDevice(xmDevInfo, true) },
//                            { addDevice(xmDevInfo, false) })
//                    } else {
//                        //"配网失败：" + errorId
//                    }
                }
            })
    }

    private fun loginDev(xmDevInfo: XMDevInfo) {
        //获取设备登录Token信息：先要登录设备，然后通过DevGetLocalEncToken来获取
        DeviceManager.getInstance()
            .loginDev(xmDevInfo.devId, object : OnDevManagerListener<Any?> {
                override fun onSuccess(
                    devId: String,
                    operationType: Int,
                    result: Any?
                ) {
                    //获取设备登录Token信息
                    val devToken = FunSDK.DevGetLocalEncToken(devId)
                    xmDevInfo.devToken = devToken
                    // 添加设备
                    XMAccountManager.getInstance().addDev(xmDevInfo, object :
                        BaseAccountManager.OnAccountManagerListener {
                        override fun onSuccess(p0: Int) {
                            // 设备添加成功
                            Toast.makeText(this@MainActivity, "设备添加成功", Toast.LENGTH_SHORT)
                                .show()
                        }

                        override fun onFailed(p0: Int, p1: Int) {
                        }

                        override fun onFunSDKResult(p0: Message?, p1: MsgContent?) {
                        }
                    })

                }

                override fun onFailed(
                    devId: String,
                    msgId: Int,
                    jsonName: String,
                    errorId: Int
                ) {
                    //失败回调 errorId是错误码
                }
            })
    }
//    /**
//     * 获取设备配网成功后的特征码，这个特征码用来给服务器校验能否能进行弱绑定，将原来已经添加到其他账号的设备重新添加当前账号
//     */
//    private fun getCloudCryNum(xmDevInfo: XMDevInfo) {
//        val devConfigManager = DeviceManager.getInstance().getDevConfigManager(xmDevInfo.devId)
//        val devConfigInfo = DevConfigInfo.create(object : OnDevManagerListener<Any?> {
//            override fun onSuccess(devId: String, operationType: Int, result: Any?) {
//                if (result is String) {
//                    try {
//                        var jsonObject: JSONObject? = JSONObject(result as String?)
//                        jsonObject = jsonObject!!.optJSONObject(GET_CLOUD_CRY_NUM)
//                        if (jsonObject != null) {
//                            val cloudCryNum = jsonObject.optString("CloudCryNum")
//                            xmDevInfo.cloudCryNum = cloudCryNum
//                        }
//                    } catch (e: Exception) {
//                        e.printStackTrace()
//                    }
//                }
//
//                addDevice(xmDevInfo, true)
//            }
//
//            override fun onFailed(devId: String, msgId: Int, jsonName: String, errorId: Int) {
//                // 获取设备特征码因为超时失败的话，可尝试重试
//                if (isNeedGetCloudTryNum && (errorId == -10005 || errorId == -100000)) {
//                    //如果获取特征码超时的话，可以延时1s重试一次
//                    Handler(Looper.getMainLooper()).postDelayed({ getCloudCryNum(xmDevInfo) }, 1000)
//
//                    isNeedGetCloudTryNum = false
//                    return
//                }
//            }
//        })
//
//        devConfigInfo.jsonName = GET_CLOUD_CRY_NUM
//        devConfigInfo.cmdId = 1020
//        devConfigManager.setDevCmd(devConfigInfo)
//    }
}